package com.lechi.web.util;

import com.lechi.web.constants.Constants;
import com.lechi.web.framework.util.GuavaCacheUtil;
import com.lechi.web.system.domain.IotMonitorDataBo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

/**
 * 指令监听器
 */
@Slf4j
public class RecordFileUtil {

    public static void producerRecord(List<IotMonitorDataBo> deviceDataList, String receiveMessage, String watchArea) {
        CompletableFuture.runAsync(() -> {
            if (deviceDataList.isEmpty()) {
                return;
            }
            IotMonitorDataBo iotMonitorDataBo = deviceDataList.get(0);
            String fileName = GuavaCacheUtil.getDeviceTableMap().get(Constants.WRITE_RECORD_LOG_TXT + iotMonitorDataBo.getDeviceId());
            if (Objects.nonNull(fileName)) {
                try {
                    fileName = fileName.replace("watchArea", watchArea);
                    Files.createDirectories(Paths.get(fileName.substring(0, fileName.lastIndexOf("/"))));
                    StandardOpenOption[] options = {StandardOpenOption.CREATE, StandardOpenOption.APPEND};
//                    Files.write(Paths.get(fileName), ("receiveTime:" + DateUtils.getTime() + ", data:" + receiveMessage + "\n").getBytes(), options);
                    Files.write(Paths.get(fileName), (receiveMessage + "\n").getBytes(), options);
                } catch (IOException e) {
                    log.error("写入传感器数据产生异常!", e);
                }
            }
        });
    }

    public static void producerRecordCsv(List<IotMonitorDataBo> deviceDataList) {
        CompletableFuture.runAsync(() -> {
            IotMonitorDataBo iotMonitorDataBo = Optional.ofNullable(deviceDataList.get(0)).orElse(new IotMonitorDataBo());
            String filePath = GuavaCacheUtil.getDeviceTableMap().get(Constants.WRITE_RECORD_LOG_CSV + iotMonitorDataBo.getDeviceId());
            if (Objects.nonNull(filePath)) {
                List<String> data = deviceDataList.stream().map(IotMonitorDataBo::getDoubleValue).toList();
                Path path = Paths.get(filePath);
                if (Files.exists(path)) {
                    writeFile(filePath, data, true);
                } else {
                    try {
                        Files.createDirectories(Paths.get(filePath.substring(0, filePath.lastIndexOf("/"))));
                    } catch (IOException e) {
                        log.error("创建文件目录异常{}", filePath, e);
                    }
                    List<String> header = deviceDataList.stream().map(IotMonitorDataBo::getSensorAliasName).toList();
                    writeFile(filePath, header, false);
                    writeFile(filePath, data, true);
                }
            }
        });

    }

    public static void writeFile(String filePath, List<String> data, Boolean isAppend) {
        try (FileWriter fileWriter = new FileWriter(filePath, isAppend); CSVPrinter csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT)) {
            csvPrinter.printRecord(data);
            csvPrinter.flush();
        } catch (Exception e) {
            log.error("写入传感器数据产生异常!", e);
        }
    }
}
